package com.sec.android.app.myfiles.launch;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.util.SemFwWrapper;

import java.io.File;

public class HandleSFinderImp extends AbsHandleLaunchImp {

    @Override
    public boolean isMyJob(Intent intent) {
        String selectedFile = intent.getDataString();
        return !TextUtils.isEmpty(selectedFile) && checkValidPath(selectedFile);
    }

    @Override
    public boolean _handleStart(int processId, Activity activity, Intent intent) {
        String path = intent.getDataString();
        if (path == null || ContextCompat.checkSelfPermission(activity.getApplicationContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        FileRecord record = FileRecord.createFileRecord(StorageType.Local, path);
        FileRecord enterFolder = record;
        FileRecord focusRecord = null;
        if (!record.isDirectory()) {
            enterFolder = record.getParent();
            focusRecord = record;
        }

        NavigationManager naviMgr = NavigationManager.getInstance(processId);
        NavigationInfo info = NavigationInfo.getInstance(NavigationInfo.NavigationMode.Normal, enterFolder);
        info.setFocusRecord(focusRecord);
        naviMgr.enter(info);

        return true;
    }

    protected boolean checkValidPath(String path) {
        File checkFile = SemFwWrapper.file(path);
        if (checkFile == null || !checkFile.exists()) {
            return false;
        }
        return true;
    }
}
